﻿using Approval.Domain;
using Contract.Domain;
using Contract.Infrastructure.Repository;
using Contract.WebApi.Application.Commands;
using MediatR;
using Newtonsoft.Json;
using PublicCommon;
using System.Collections.Generic;

namespace Contract.WebApi.Application.CommandHandler
{
    public class AddHZContractCommandHandler : IRequestHandler<AddHZContractCommands, int>
    {
        private readonly IRepository<Domain.Contract> repository;
        private readonly Cross_services_Helper cross_services_helper;
        private readonly IRepository<Tail> repository1;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="repository"></param>
        public AddHZContractCommandHandler(Infrastructure.Repository.IRepository<Domain.Contract> repository, Cross_services_Helper cross_services_helper, IRepository<Tail> repository1)
        {
            this.repository = repository;
            this.cross_services_helper = cross_services_helper;
            this.repository1 = repository1;
        }

        /// <summary>
        /// 添加货主合同
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<int> Handle(AddHZContractCommands request, CancellationToken cancellationToken)
        {
            DateTime now = DateTime.Now;
            string serialNumber = now.ToString("yyyyMMddHHmmss");
            request.ContractNumber = "HZ" + serialNumber;
            request.ContractType = 1;
            request.AuditState = 1;
            var inf = await repository.AddAsync(request);

            var list = await repository.GetAsync(x => x.ContractNumber == request.ContractNumber);

            var obj = new HCTRelation();
            obj.HCTId = list.ContractNumber;
            obj.ApprovalId = 4;
            obj.ApprovalName = "小明";
            var message = await cross_services_helper.Post("http://10.31.60.9:8000/Approval/api/HCTRelation/HCTRelationAdd", obj);
            if (Convert.ToInt32(message) < 0)
            {
                return await Task.FromResult(-1);
            }

            var res = await cross_services_helper.Get($"http://10.31.60.9:8000/LongLine/api/LineInfo/GetLineRoute");
            var line = JsonConvert.DeserializeObject<List<LineDto>>(res);
            var ind = line.FirstOrDefault(x=>x.Id==list.Route);
            Tail tail = new Tail();
            tail.ContractNumber = list.ContractNumber;
            tail.Shipping = ind.Address;
            tail.CreateDate = list.CreateDate;
            tail.ShipperEnterprise = list.ShipperEnterprise;
            tail.Responsible = list.Responsible;
            tail.TrackingState = "合同已创建";
            await repository1.AddAsync(tail);

            return inf;
        }
    }
}
